//
//  AppAPIClient.m
//  drinkApp
//
//  Created by cnbizMedia on 14/6/24.
//  Copyright (c) 2014年 CnbizMedia. All rights reserved.
//

#import "AppAPIClient.h"
#import "Util.h"
static NSString * const MSAppAPIBaseURLString = @"http://ksjv2.kanshangjie.com";
@interface AppAPIClient()
@property(nonatomic,strong) NSString *name;
@property(nonatomic,strong) NSString *cookie;
@property(nonatomic,strong) NSString *token;
@end
@implementation AppAPIClient
+ (instancetype)sharedClient {
    static AppAPIClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[AppAPIClient alloc] initWithBaseURL:[NSURL URLWithString:MSAppAPIBaseURLString]];
    });
    
    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
        //[self setSecurityPolicy:[AFSecurityPolicy
        //policyWithPinningMode:AFSSLPinningModeCertificate]];
        int cacheSizeMemory = 1*1024*1024; // 4MB
        int cacheSizeDisk = 100*1024*1024; // 100MB
        [[NSURLCache sharedURLCache] setMemoryCapacity:cacheSizeMemory];
        [[NSURLCache sharedURLCache] setDiskCapacity:cacheSizeDisk];
        
        AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
        [requestSerializer setValue:[UIDevice currentDevice].name forHTTPHeaderField:@"X-Device-Name"];
        [requestSerializer setValue:[OpenUDID_UDID value] forHTTPHeaderField:@"X-Device-UDID"];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"X-Device-Token"]) {
            NSString*str=[[NSUserDefaults standardUserDefaults] objectForKey:@"X-Device-Token"];
            [requestSerializer setValue:str forHTTPHeaderField:@"X-Device-Token"];
        }
        
        self.token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
        if (self.token) {
            [requestSerializer setValue:self.token forHTTPHeaderField:@"X-Token-Val"];
        }
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript" ,@"text/plain", nil];
        [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        NSLog(@"TOKEN:%@",self.token);
        [self setRequestSerializer:requestSerializer];
    }
    return self;
}

- (void)setTokenA:(NSString *)token{
    if ([self.token isEqualToString:token]) {
        return;
    }
    if([token isEqualToString:@""]){
        self.cookie = @"";
        _name = @"";
    }
    self.token = token;
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    [requestSerializer setValue:[UIDevice currentDevice].name forHTTPHeaderField:@"X-Device-Name"];
    [requestSerializer setValue:[OpenUDID_UDID value] forHTTPHeaderField:@"X-Device-UDID"];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"X-Device-Token"]) {
        NSString*str=[[NSUserDefaults standardUserDefaults] objectForKey:@"X-Device-Token"];
        [requestSerializer setValue:str forHTTPHeaderField:@"X-Device-Token"];
    }
    if (token.length>3) {
        [requestSerializer setValue:self.token forHTTPHeaderField:@"X-Token-Val"];
    }
    [self setRequestSerializer:requestSerializer];
//    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
}
- (void)setDeviceToken:(NSString *)DeviceToken{
    if ([DeviceToken isEqualToString:[UserDefaults objectForKey:@"X-Device-Token"]]) {
        return;
    }
    if([DeviceToken isEqualToString:@""]){
        [UserDefaults setValue:@"" forKey:@"X-Device-Token"];
    }else{
    [UserDefaults setValue:DeviceToken forKey:@"X-Device-Token"];
    }
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    [requestSerializer setValue:[UIDevice currentDevice].name forHTTPHeaderField:@"X-Device-Name"];
    [requestSerializer setValue:[OpenUDID_UDID value] forHTTPHeaderField:@"X-Device-UDID"];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"X-Device-Token"]) {
        NSString*str=[[NSUserDefaults standardUserDefaults] objectForKey:@"X-Device-Token"];
        [requestSerializer setValue:str forHTTPHeaderField:@"X-Device-Token"];
    }
    if (self.token.length>3) {
        [requestSerializer setValue:self.token forHTTPHeaderField:@"X-Token-Val"];
    }
    [self setRequestSerializer:requestSerializer];
    //    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
}

- (void) checkErrorCode:(NSDictionary*)response{
    int code = [response[@"code"] intValue];
    if(code == 300){
        self.token = nil;
        self.cookie = nil;
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"token"];
        //[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
    }
}

- (AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure {
    //URLString = [NSString stringWithFormat:@"access.php"];
    if(![URLString hasPrefix:@"http"]){
        URLString = [NSString stringWithFormat:@"%@/%@",MSAppAPIBaseURLString,URLString];
    }
    
    NSString *string             = [[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString];
    
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:string parameters:parameters error:nil];//[self.requestSerializer requestWithMethod:@"GET" URLString:string parameters:parameters];
    NSLog(@"URL:%@ Req:%@",string,request);
    /*
    if (![AFNetworkReachabilityManager sharedManager].reachable) {
        request.cachePolicy = NSURLRequestReturnCacheDataDontLoad;
    }else {
        request.cachePolicy = NSURLRequestReloadIgnoringCacheData;
    }*/
    if (self.cookie) {
        [request setValue:_cookie forHTTPHeaderField:_name];
    }
    /*
    if (self.token) {
        [request setValue:self.token forHTTPHeaderField:@"X-Token-Val"];
    }*/
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[operation.response allHeaderFields] forURL:operation.request.URL];
        NSHTTPCookie *cookie = [cookies lastObject];
        if (!self.cookie) {
            self.cookie = [cookie value];
            self.name   = [cookie name];
        }
        if (success) {
            [self checkErrorCode:responseObject];
            success(operation,responseObject);
        }
        
    } failure:failure];
    
    [self.operationQueue addOperation:operation];
    return operation;
}

- (AFHTTPRequestOperation *)UPLOAD:(NSString *)URLString name:(NSString*)name withImage:(UIImage*)image constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure{
    
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:nil constructingBodyWithBlock:block error:nil];
    //NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:URLString parameters:parameters constructingBodyWithBlock:success error:failure];
    if (self.cookie) {
        [request setValue:_cookie forHTTPHeaderField:_name];
    }
    if (self.token) {
        [request setValue:self.token forHTTPHeaderField:@"X-Token-Val"];
    }
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[operation.response allHeaderFields] forURL:operation.request.URL];
        NSHTTPCookie *cookie = [cookies lastObject];
        if (!self.cookie) {
            self.cookie = [cookie value];
            self.name   = [cookie name];
        }
        if (success) {
            [self checkErrorCode:responseObject];
            /*
             if([responseObject containsValueForKey:@"data"] && [responseObject[@"data"] containsValueForKey:@"token"]){
             if([self.token isEqualToString:@""]){
             self.token = responseObject[@"data"][@"token"];
             }
             }*/
            success(operation,responseObject);
        }
    } failure:failure];
    [self.operationQueue addOperation:operation];
    
    return operation;
}

- (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure {
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block];
    //NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:URLString parameters:parameters constructingBodyWithBlock:success error:failure];
    if (self.cookie) {
        [request setValue:_cookie forHTTPHeaderField:_name];
    }
    if (self.token) {
        [request setValue:self.token forHTTPHeaderField:@"X-Token-Val"];
    }
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[operation.response allHeaderFields] forURL:operation.request.URL];
        NSHTTPCookie *cookie = [cookies lastObject];
        if (!self.cookie) {
            self.cookie = [cookie value];
            self.name   = [cookie name];
        }
        if (success) {
            [self checkErrorCode:responseObject];
            /*
            if([responseObject containsValueForKey:@"data"] && [responseObject[@"data"] containsValueForKey:@"token"]){
                if([self.token isEqualToString:@""]){
                    self.token = responseObject[@"data"][@"token"];
                }
            }*/
            success(operation,responseObject);
        }
    } failure:failure];
    [self.operationQueue addOperation:operation];
    
    return operation;
}

- (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure {
    
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];

    if (self.cookie) {
        [request setValue:_cookie forHTTPHeaderField:_name];
    }
    if (self.token) {
        [request setValue:self.token forHTTPHeaderField:@"X-Token-Val"];
    }
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[operation.response allHeaderFields] forURL:operation.request.URL];
        NSHTTPCookie *cookie = [cookies lastObject];
        if (!self.cookie) {
            self.cookie = [cookie value];
            self.name   = [cookie name];
        }
        if (success) {
            [self checkErrorCode:responseObject];
            success(operation,responseObject);
        }
        //NSLog(@"%@",[[operation.request allHTTPHeaderFields] description]);
        //NSLog(@"%@",[responseObject description]);
    }failure:failure];
    [self.operationQueue addOperation:operation];
    
    return operation;
}
@end
